<?php
namespace api\modules\v1\controllers;

use api\common\controllers\Controller;
use common\records\Chargement;
use common\records\UserInfo;
use common\records\Record;
use api\common\tools\WxPayResults;
use api\common\tools\WxPayConfig;
use api\common\tools\WxPayException;


class CallbackController extends Controller
{
    /**
     * @api {post} /v1/callback/pay 支付回调
     * @apiVersion 1.0.0
     * @apiName pay
     * @apiGroup callback
     *
     *
     */
    public function  actionPay()
    {

        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $result = WxPayResults::Init($xml);
        $resp = array();
        if($result['return_code'] == "SUCCESS" && $result['result_code'] == "SUCCESS")
        {
            $out_trade_no = $result['out_trade_no'];
            $chargement = Chargement::find()->where(['out_trade_no'=>$out_trade_no])->one();

            if($chargement == null || $chargement->status != 0)
            {
                return;
            }
            $chargement->status = 1;
            $chargement->pay_time = date('Y-m-d H:i:s',time());

            $uid = $chargement->uid;
            $user = UserInfo::find()->where(['uid'=>$uid])->one();
            $user->coin = $user->coin + $chargement->coin;
            $user->save(false);
            $chargement->save(false);

            $record = new Record();
            $record->uid = $uid;
            $record->coin = $chargement->coin;
            $record->type = 1;
            $desp  = "充值".$chargement->money."元";
            $record->description = $desp;
            $record->timestamp = $chargement->pay_time;
            $record->status = 1;
            $record->save();
        }else{
            $out_trade_no = $result['out_trade_no'];
            $chargement = Chargement::find()->where(['out_trade_no'=>$out_trade_no])->one();

            if($chargement == null || $chargement->status != 0)
            {
                return;
            }
            $chargement->status = 2;
            $chargement->pay_time = date('Y-m-d H:i:s',time());
            $chargement->save(false);
        }
    }
    
}
